﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace TM.QWeibo.Client.UserControls
{
    public partial class TAd
    {
        Helper.AdHelper _adHelper=new Helper.AdHelper();

        public TAd()
        {
            InitializeComponent();
            adImage.Width = App.Current.RootVisual.RenderSize.Width;
            adImage.Height = App.Current.RootVisual.RenderSize.Height;
            _backgroundWorker=new BackgroundWorker {WorkerSupportsCancellation = true};
            RunBackgroundWorker();
        }

        private BackgroundWorker _backgroundWorker;

        public Action Tapped;

        public void Show(Action callback)
        {
            if(!_adHelper.HasAdToBeShow)
            {
                homeAdPopUp.IsOpen = false;
                callback();
                return;
            }
            adImage.Source = _adHelper.Get();
            Tapped = callback;
            homeAdPopUp.IsOpen = true;
            App.IsShowAdd = true;
            PopupOnStoryboard.Resume();
        }

        private void adImage_Tap(object sender, GestureEventArgs e)
        {
            if(_backgroundWorker==null)
            {
                return;
            }
            _backgroundWorker.CancelAsync();
            _backgroundWorker = null;
            PopupOnStoryboard.Begin();
            if (Tapped!=null)
            {
                Tapped();
            }
        }

        private void RunBackgroundWorker()
        {
            _backgroundWorker.DoWork += ((s, args) => Thread.Sleep(AppSetting.AdHideDelay));
            _backgroundWorker.RunWorkerCompleted += ((s, args) => Dispatcher.BeginInvoke(() => adImage_Tap(null,null)));
            _backgroundWorker.RunWorkerAsync();
        }

    }
}
